/**********************************************************
 * Copyright © 2008，北京福富软件技术股份有限公司
 * All Rights Reserved.
 *
 * 文件名称： UploadController.java
 * 摘    要：
 *
 * 初始版本：1.0.0
 * 原 作 者：RUN
 * 完成日期：2009-9-4
 *
 * 当前版本：$LastChangedRevision$
 * 作    者：$LastChangedBy$
 * 完成日期：$LastChnagedDate$
 ************************************************************/
package aip.ui.attachment.web.spring;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import aip.core.model.attachment.Attachment;
import aip.core.model.attachment.Photo;
import aip.ui.attachment.srvc.AttachmentService;
import aip.ui.attachment.util.ThumbnailUtils;

import com.googlecode.horncomb.web.spring.mvc.FormServiceController;

/**
 * UploadController
 * <p>
 * 负责人/principal: Daniel<br/>
 * 修改记录/revision:<br/>
 * 日期:<br/>
 * 修改人:<br/>
 * 修改说明:
 * @author RUN
 * @version $Id: codetemplates.xml 2007 2009-05-08 08:36:14Z shiw $
 */
public class UploadController extends FormServiceController<AttachmentService>
{
    // 缩略图宽\高
    public static final int THUMBNAIL_WIDTH = 200;
    public static final int THUMBNAIL_HEIGHT = 150;

    public ModelAndView save(HttpServletRequest request,
            HttpServletResponse response, UploadForm form) throws Exception
    {
        form.setAttachments(new ArrayList<Attachment>());
        String savedFile = "";
        String unSavedFile = "";

        // 上传附件
        if (request instanceof MultipartHttpServletRequest)
        {
            MultipartHttpServletRequest mpReq = (MultipartHttpServletRequest) request;
            for (Iterator<?> i = mpReq.getFileNames(); i.hasNext();)
            {
                MultipartFile mpfile = mpReq.getFile(i.next().toString());
                if (mpfile.getSize() > 0)
                {
                    Attachment file = this.transferToFile(form, mpfile);
                    form.getAttachments().add(file);
                    if (savedFile.length() > 0)
                    {
                        savedFile = savedFile.concat(",");
                    }
                    savedFile = savedFile.concat("[").concat(
                            mpfile.getOriginalFilename()).concat("]");
                }
                else
                {
                    if (unSavedFile.length() > 0)
                    {
                        unSavedFile = unSavedFile.concat(",");
                    }
                    unSavedFile = unSavedFile.concat("[").concat(
                            mpfile.getOriginalFilename()).concat("]文件大小为0");
                }
            }
            // form的id不为空，则为编辑照片操作
            if (form.getAtchType().indexOf(Attachment.TYPE_PHOTO) != -1
                    && form.getId() != 0 && form.getAttachments().size() == 1)
            {
                this.formService.updatePhoto((Photo) form.getAttachments().get(
                        0));
            }
            else
            {
                this.formService.save(form);
            }
            if (savedFile.length() > 0)
            {
                form.setResult(savedFile.concat("，上传成功"));
            }
            if (unSavedFile.length() > 0)
            {
                if (StringUtils.hasText(form.getResult()))
                {
                    form.setResult(form.getResult().concat("<br />").concat(
                            unSavedFile).concat("，上传失败"));
                }
                else
                {
                    form.setResult(unSavedFile.concat("，上传失败"));
                }
            }
        }
        // 照片附件没有上传新照片时，更新照片信息
        else
        {
            form.getAttachments().add(form.getPhoto());
            this.formService.save(form);
        }

        Map<String, Object> model = this.formService.listReference(form);
        model.put(this.getCommandName(), form);
        String view = (String) this
                .resolveEventView(request, form, null, model);
        view = StringUtils.hasText(view) ? view : this.getFormView();
        return new ModelAndView(view, model);
    }

    public ModelAndView delete(HttpServletRequest request,
            HttpServletResponse response, UploadForm form) throws Exception
    {
        this.formService.delete(form);
        Map<String, Object> model = this.formService.listReference(form);
        model.put(this.getCommandName(), form);
        String view = (String) this
                .resolveEventView(request, form, null, model);
        view = StringUtils.hasText(view) ? view : this.getFormView();
        return new ModelAndView(view, model);
    }

    /**
     * 将mpfile转化为自定义的附件格式
     * @param form
     * @param mpfile
     * @return
     * @throws Exception
     */
    protected Attachment transferToFile(UploadForm form, MultipartFile mpfile)
            throws Exception
    {
        Attachment attachment = form.getAtchType().indexOf(
                Attachment.TYPE_PHOTO) != -1 ? new Photo() : new Attachment();

        // 图片附件，生成缩略图
        if (attachment instanceof Photo)
        {
            Photo photo = (Photo) attachment;
            PropertyUtils.copyProperties(photo, form.getPhoto());
            int width = THUMBNAIL_WIDTH, height = THUMBNAIL_HEIGHT;
            BufferedImage srcImage;
            String imgType = "JPEG";
            srcImage = ImageIO.read(mpfile.getInputStream());
            if (width > 0 || height > 0)
            {
                srcImage = ThumbnailUtils.resize(srcImage, width, height);
            }
            ByteArrayOutputStream thumbnail = new ByteArrayOutputStream();
            ImageIO.write(srcImage, imgType, thumbnail);

            // 图片文件及缩略图较小,使用byte存储
            photo.setContent(mpfile.getBytes());
          //  photo.setThumbnail(thumbnail.toByteArray());
        }
        else
        {
            // 通用附件可能存在大文件,防止outofmemory发生,统一使用inputStream
            attachment.setContent(mpfile.getInputStream());
        }

        attachment.setType(form.getAtchType());
        // attachment.setCreator(UserHelper.getCurrentUser().getId());
        attachment.setCreate(new Date());
        attachment.setEntityRefId(form.getEntityRefId());

        String fileName = mpfile.getOriginalFilename();
        int idx = fileName.lastIndexOf(".");
        attachment.setName(idx == -1 ? fileName : fileName.substring(0, idx));
        attachment.setExtension(idx == -1 ? ".txt" : fileName.substring(idx,
                fileName.length()));

        return attachment;
    }
}
